package top.hudk.file;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 请输入描述信息
 *
 * @author HuDongkang
 * @date 2022/2/13 21:47
 */
public class FileTest {


    public static void main(String[] args) {
        FileTest fileTest = new FileTest();
        fileTest.test();
    }



    public void test(){
        List<File> fileList = new ArrayList<>();
        String newPath = "/Users/bailongma/Downloads/家庭教育宝典/";
        File directory = new File("/Users/bailongma/Downloads/Dr魏的家庭教育宝典（完结）");
        collectFiles(directory, fileList);
        List<String> collectJpg = fileList.stream().map(File::getName).filter(name -> name.endsWith("jpg")).collect(Collectors.toList());
        List<String> collectMp3 = fileList.stream().map(File::getName).filter(name -> name.endsWith("mp3")).collect(Collectors.toList());

        collectJpg.forEach(System.out::println);
        collectMp3.forEach(System.out::println);

        fileList.forEach(file -> {
            String name = file.getName();
            if(!name.endsWith(".mp3")){
                return;
            }
            String tile = getTile(name.substring(0, name.indexOf(".mp3")).trim(), collectJpg);
            System.out.println(tile);
            if(StrUtil.isNotBlank(tile)){
                tile = tile + ".mp3";
            }else {
                tile = name;
            }
            FileUtil.copyFile(file, new File(newPath + tile));
        });
    }

    public String getTile(String x,List<String> collectJpg){
        List<String> collect = collectJpg.stream().filter(jpg -> jpg.startsWith(x)).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(collect)){
            return "";
        }
        String fileName = collect.get(0);
        return fileName.substring(0,fileName.indexOf(".jpg")).trim();
    }

    /**
     * 将指定的抽象路径中所有的文件放入指定的List中
     * @param directory 路径
     * @param fileList
     */
    public void collectFiles(File directory, List<File> fileList){
        if(Objects.isNull(directory)){
            return;
        }
        if(directory.isFile()){
            fileList.add(directory);
            return;
        }
        File[] files = directory.listFiles();
        if(Objects.nonNull(files)){
            for(File file : files){
                if(file.isDirectory()){
                    collectFiles(file, fileList);
                }else {
                    fileList.add(file);
                }
            }
        }
    }



}
